package com.example;

import com.example.handler.InServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class NettyServer {
	private final int port; //监听端口

    public NettyServer(int port) {
        this.port = port;
    }

    public void run() throws Exception{
    	NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        try {
			serverBootstrap.group(bossGroup, workerGroup) // 配置线程组
					.channel(NioServerSocketChannel.class) // 配置IO模型
					.option(ChannelOption.SO_BACKLOG, 1024).childOption(ChannelOption.SO_KEEPALIVE, true)
					.childHandler(new ChannelInitializer<NioSocketChannel>() { // 匿名内部类，处理逻辑
						protected void initChannel(NioSocketChannel ch) {
							// 处理逻辑
							ch.pipeline().addLast("decoder", new StringDecoder());
							ch.pipeline().addLast("encoder", new StringEncoder());
							ch.pipeline().addLast(new InServerHandler());
						}
					});
			ChannelFuture channelFuture = serverBootstrap.bind(port).sync(); // 绑定端口

			// 监听关闭
			channelFuture.channel().closeFuture().sync();
		} finally {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
    }
}
